<template>
  <div class="dishes-index">
    <el-card class="page-card">
      <div class="page-header">
        <h2>菜品管理</h2>
        <el-button type="success" @click="showAddDialog" icon="Plus">新增菜品</el-button>
      </div>

      <!-- 查询表单 -->
      <el-form :model="dishes" ref="formRef" label-width="120px" label-position="right" class="search-form">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="菜名" prop="name">
              <el-input v-model="dishes.name" placeholder="请输入菜名" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="价格" prop="price">
              <el-input v-model="dishes.price" placeholder="请输入价格" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="状态" prop="state">
              <el-select v-model="dishes.state" placeholder="状态" clearable>
                <el-option label="全部" value="" />
                <el-option label="上架" value="1" />
                <el-option label="下架" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="分类" prop="dishes_class">
              <el-input v-model="dishes.dishes_class" placeholder="请输入类型" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="search-buttons">
            <el-space>
              <el-button type="primary" @click="doList" icon="Search">查询</el-button>
              <el-button type="default" @click="resetForm(formRef)" icon="Refresh">重置</el-button>
            </el-space>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" stripe hover-row border style="width: 100%" class="data-table">
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <el-table-column prop="id" label="ID" align="center"/>
        <el-table-column prop="name" label="菜名" align="center"/>
        <el-table-column prop="price" label="价格" align="center"/>
        <el-table-column prop="state" label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.state == 1" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="picture" label="图片" align="center"/>
        <el-table-column prop="dishes_class" label="分类" align="center"/>
        <el-table-column label="操作" width="280" align="center">
          <template #default="scope">
            <el-space size="small">
              <el-button type="primary" size="small" @click="showDetailPage(scope.row)" icon="View">详情</el-button>
              <el-button type="warning" size="small" @click="showUpdateDialog(scope.row)" icon="Edit">更新</el-button>
              <el-button type="danger" size="small" @click="doDelete(scope.row.id)" icon="Delete">删除</el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增菜品" width="50%" top="10vh" destroy-on-close>
      <add-page @flushPage="doFlushPage" @closeDialog="addDialogVisible = false"/>
    </el-dialog>

    <!-- 更新对话框 -->
    <el-dialog v-model="updateDialogVisible" title="更新菜品" width="50%" top="10vh" destroy-on-close>
      <update-page ref="updatePageRef" @flushPage="doFlushPage" @closeDialog="updateDialogVisible = false"/>
    </el-dialog>

    <!-- 详情页面 -->
    <detail-page ref="detailPageRef"/>
  </div>
</template>

<style scoped>
.dishes-index {
  padding: 20px;
}

.page-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.search-form {
  padding: 0 20px 20px;
}

.search-buttons {
  display: flex;
  align-items: center;
  margin-top: -18px;
}

.data-table {
  margin: 0 20px 20px;
}

.pagination {
  margin: 0 20px 20px;
  text-align: right;
}
</style>

<script setup lang="ts">
import {ref, onMounted, nextTick} from 'vue'
import {ElMessage, FormInstance} from "element-plus";
import axios from 'axios'
import DetailPage from './DetailPage.vue';
import AddPage from './AddPage.vue';
import UpdatePage from './UpdatePage.vue';

const formRef = ref<FormInstance>();
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 获取当前店铺ID
const shopId = localStorage.getItem('shopInfo') ? JSON.parse(localStorage.getItem('shopInfo')).id : null;

if (!shopId) {
    ElMessage.error('未找到店铺信息，请先从商家列表进入');
}

// form 查询表单绑定的数据对象：dishes
const dishes = ref({
    id: '',
    name: '',
    price: '',
    shop_id: shopId,
    state: '',
    picture: '',
    dishes_class: ''
});

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// table 数据表格绑定的数据对象：tableData
const tableData = ref([]);

// 查询
// 处理分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val;
    doList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val;
    doList();
};

const doList = async () => {
    // 调用后端接口获取店铺信息
    const { data} = await axios.get('/api/dishes',{params: {...dishes.value, page: currentPage.value, pageSize: pageSize.value}});
    tableData.value = data.list || data;
    // 假设返回的数据中有total字段
    if(data && data.total) {
        total.value = data.total;
    }
}

// 删除
const doDelete = async (id) => {
    const {data} = await axios.delete(`/api/dishes/${id}`);
    if (data > 0) {
        doFlushPage();		// 删除成功，刷新表格数据
        ElMessage.success('删除成功');
    } else {
        ElMessage.error('删除失败');
    }
}

// 刷新页面
const doFlushPage = () => {
    resetForm(formRef.value);
    doList();
}

// 初始化
onMounted(() => {
    doList();   // 查询数据
})

//--------------------------- 新增 对话框 ---------------------------
const addDialogVisible = ref(false);
const showAddDialog = () => {
    addDialogVisible.value = true;
}

//--------------------------- 更新 对话框 ---------------------------
const updateDialogVisible = ref(false);
const updatePageRef = ref(); // 组件引用
const showUpdateDialog = (obj) => {
    updateDialogVisible.value = true;
    nextTick(() => {
        updatePageRef.value.handleUpdateData(obj);
    })
}

//--------------------------- 详显 页面---------------------------
// 详显组件引用 -> 绑定到
const detailPageRef = ref();
const showDetailPage = (obj) => {
    detailPageRef.value.handleDetailData(obj);
}
</script>